<template>
  <Modal
    :action="true"
    width="749px"
    :visible="modalProps.visible"
    :title="`编辑`"
    @confirm="onConfirm"
    :confirm-loading="editLoading"
    @close="onVisible(false)"
    destroy-on-close
  >
    <template #body>
      <el-form
        ref="formRef"
        :rules="rules"
        :model="formData"
        label-width="118px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="投放日期" prop="putTm">
              <el-input
                placeholder="请输入投放日期"
                maxlength="32"
                disabled
                clearable
                v-model="formData.putTm"
              />
            </el-form-item>
            <el-form-item label="施工号" prop="constructionNo">
              <el-input
                placeholder="请输入施工号"
                maxlength="32"
                disabled
                clearable
                v-model="formData.constructionNo"
              />
            </el-form-item>
            <el-form-item label="类别" prop="type">
              <el-select
                v-model="formData.type"
                placeholder="请选择类别"
                style="width: 100%"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.key"
                  :label="item.val"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="排产日期" prop="prodTm">
              <el-date-picker
                v-model="formData.prodTm"
                @change="convert(formData.prodTm, 'prodTm')"
                type="date"
                placeholder="请输入排产日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="DK计划完工日期" prop="dkCompleteTm">
              <el-date-picker
                v-model="formData.dkCompleteTm"
                @change="convert(formData.dkCompleteTm, 'dkCompleteTm')"
                type="date"
                placeholder="请输入DK计划完工日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="阀计划完工日期" prop="valveCompleteTm">
              <el-date-picker
                v-model="formData.valveCompleteTm"
                type="date"
                @change="convert(formData.valveCompleteTm, 'valveCompleteTm')"
                placeholder="请输入阀计划完工日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="销售员" prop="salesperson">
              <el-input
                placeholder="请输入销售员"
                maxlength="32"
                disabled
                clearable
                v-model="formData.salesperson"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新日期" prop="prodUpdTm">
              <el-input
                placeholder="请输入更新日期"
                maxlength="32"
                disabled
                clearable
                v-model="formData.prodUpdTm"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialNm">
              <el-input
                placeholder="请输入物料名称"
                maxlength="32"
                disabled
                clearable
                v-model="formData.materialNm"
              />
            </el-form-item>
            <el-form-item label="客户需求日期" prop="demandTm">
              <el-input
                placeholder="请输入客户需求日期"
                maxlength="32"
                disabled
                clearable
                v-model="formData.demandTm"
              />
            </el-form-item>
            <el-form-item label="采购回复日期" prop="buyerReplyTm">
              <el-date-picker
                v-model="formData.buyerReplyTm"
                type="date"
                @change="convert(formData.buyerReplyTm, 'buyerReplyTm')"
                placeholder="请输入采购回复日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="工区回复日期" prop="producerReplyTm">
              <el-date-picker
                v-model="formData.producerReplyTm"
                type="date"
                @change="convert(formData.producerReplyTm, 'producerReplyTm')"
                placeholder="请输入工区回复日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="是否完工" prop="isComplete">
              <el-input
                placeholder="请输入是否完工"
                maxlength="32"
                disabled
                clearable
                v-model="formData.isComplete"
                :value="formData.isComplete ? '是' : '否'"
              />
            </el-form-item>
            <el-form-item label="排产人员" prop="producer">
              <el-input
                placeholder="请输入排产人员"
                maxlength="32"
                disabled
                clearable
                v-model="formData.producer"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入备注"
            maxlength="200"
            clearable
            v-model="formData.remark"
          />
        </el-form-item>
      </el-form>
    </template>
  </Modal>
</template>

<script setup lang="ts">
  import { ref, reactive, nextTick } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { usePost, Modal } from '@hdzk-hel/pangu'
  import { formatting } from '../constants'
  import { cloneDeep } from 'lodash'

  const typeList = reactive([
    {
      key: '1',
      val: 'DK'
    },
    {
      key: '2',
      val: '阀'
    },
    {
      key: '3',
      val: '阀+DK'
    }
  ])

  // type Props = {
  // 	dayList: ObjectType[];
  // };
  // const props = withDefaults(defineProps<Props>(), {
  // 	dayList: () => []
  // });
  type ObjectType = {
    [key: string]: any
  }
  // interface Irow {
  // 	startTime: string;
  // 	endTime: string;
  // }
  interface FormData {
    putTm?: string | undefined
    prodUpdTm?: string | undefined
    constructionNo?: string | undefined
    materialNm?: string | undefined
    type?: string | undefined
    demandTm?: string | undefined
    prodTm?: string | undefined
    buyerReplyTm?: string | undefined
    producerReplyTm?: string | undefined
    dkCompleteTm?: string | undefined
    valveCompleteTm?: string | undefined
    isComplete?: string | undefined
    salesperson?: string | undefined
    producer?: string | undefined
    remark?: string | undefined
  }

  const formRef = ref<FormInstance>()

  const { runAsync: fetchEdit, loading: editLoading } = usePost(
    'POST',
    '/aps/v1/api/planProduction/updatePlan'
  )
  // const { runAsync: fetchAddOrEdit, loading: editLoading } = usePost("POST", "/device/v1/api/planClassFrequency/saveOrEdit");
  //  工作日字典
  // const { runAsync: fetchDictList } = usePost("POST", "/v1/dict/queryList");
  interface ModalProps {
    visible: boolean
    type: '新增' | '编辑'
    rowData?: FormData
    getTableList?: Function
  }

  //弹框prop
  const modalProps = ref<ModalProps>({
    visible: false,
    type: '新增'
  })
  const defaultForm = {
    putTm: '',
    prodUpdTm: '',
    constructionNo: '',
    materialNm: '',
    type: '',
    demandTm: '',
    prodTm: '',
    buyerReplyTm: '',
    producerReplyTm: '',
    dkCompleteTm: '',
    valveCompleteTm: '',
    isComplete: '',
    salesperson: '',
    producer: '',
    remark: ''
  }
  //表单数据
  const formData = ref<FormData>(JSON.parse(JSON.stringify(defaultForm)))
  const titleType: ObjectType = {
    edit: '编辑',
    add: '新增'
  }
  //表单校验
  const rules = reactive({
    // trigger: "blur" 输入的
    type: [{ required: false, message: '请选择类别', trigger: 'change' }],
    prodTm: [{ required: false, message: '请选择排产日期', trigger: 'change' }],
    buyerReplyTm: [
      { required: false, message: '请选择采购回复日期', trigger: 'change' }
    ],
    producerReplyTm: [
      { required: false, message: '请选择工区回复日期', trigger: 'change' }
    ],
    dkCompleteTm: [
      { required: false, message: '请选择DK计划完工日期', trigger: 'change' }
    ],
    valveCompleteTm: [
      { required: false, message: '请选择阀计划完工日期', trigger: 'change' }
    ],
    remark: [{ required: false, message: '请输入备注', trigger: 'blur' }]
  })

  // 打开弹框
  const onVisible = (visible: boolean, title?: string) => {
    modalProps.value.visible = visible
    if (title) {
      modalProps.value.type = titleType[title]
    }
    if (!visible) {
      formData.value = JSON.parse(JSON.stringify(defaultForm))
    }
  }
  // 编辑
  const acceptParams = (params: ObjectType) => {
    modalProps.value.getTableList = params.getTableList
    if (!Object.keys(params.row).length) {
      nextTick(() => {
        formRef.value && formRef.value!.clearValidate()
      })
      return
    }
    const row = JSON.parse(JSON.stringify(params.row))
    row.putTm = formatting(row.putTm, 'date')
    row.demandTm = formatting(row.demandTm, 'date')
    row.prodUpdTm = formatting(row.prodUpdTm, 'date')
    formData.value = row
  }
  // 转换
  const convert = (originalTime: string | undefined, key: string) => {
    if (!originalTime) {
      ;(formData.value as Record<string, string | undefined>)[key] = ''
      console.log((formData.value as Record<string, string | undefined>)[key])
    } else {
      const formattedTime = formatting(originalTime, 'time')
      console.log(formattedTime)
      ;(formData.value as Record<string, string | undefined>)[key] =
        formattedTime
    }
  }
  const fieldsToDelete = [
    'prodUpdTm',
    'createTime',
    'createUser',
    'demandUpdTm',
    'isComplete',
    'isDeleted',
    'materialCd',
    'materialNm',
    'salesperson',
    'salespersonNo',
    'updateTime',
    'updateUser',
    'putTm'
  ]
  const onConfirm = async () => {
    const sendParams = cloneDeep(formData.value)
    sendParams.demandTm = formatting(sendParams.demandTm, 'time')
    fieldsToDelete.forEach(field => {
      delete sendParams[field]
    })
    try {
      const { ok } = await fetchEdit(sendParams)
      if (ok) {
        modalProps.value.getTableList!()
        onSusccess()
      }
    } catch (error) {
      throw error
    }
  }

  const onSusccess = () => {
    ElMessage.success({ message: '操作成功' })
    onVisible(false)
  }
  defineExpose({
    acceptParams,
    onVisible
  })
</script>
